﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Dycox.Collections
{
    public abstract class OwnedCollection<TItem, TOwner> : CollectionBase<TItem>
        where TItem : class
        where TOwner: class
    {
        TOwner _owner;

        protected OwnedCollection(TOwner owner)
        {
            if (owner == null)
                throw new ArgumentNullException("owner");
            
            _owner = owner;
        }

        public TOwner Owner
        {
            get { return _owner; }
        }

        protected abstract void SetItemOwner(TItem item, TOwner owner);

        protected abstract TOwner GetItemOwner(TItem item);

        protected override void AttachItem(TItem item)
        {
            base.AttachItem(item);

            TOwner parent = GetItemOwner(item);
            if (parent != null)
            {
                if (!object.ReferenceEquals(parent, _owner)) throw new InvalidOperationException("This item belongs to another collection.");
                else return;
            }

            SetItemOwner(item, _owner);
        }

        protected override void DeattachItem(TItem item)
        {
            base.DeattachItem(item);

            TOwner parent = GetItemOwner(item);
            if (parent != null)
            {
                if (!object.ReferenceEquals(parent, _owner))
                    throw new InvalidOperationException("This item does not belong to this collection.");
                SetItemOwner(item, null);
            }
        }


    }

    public abstract class OwnedCollection<T> : OwnedCollection<T, T>
        where T : class
    {
        protected OwnedCollection(T owner)
            : base(owner)
        {
        }
    }
}
